﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rud.Holmgren.Tabulex3000.Util
{
    public class AppSettings : INotifyPropertyChanged
    {
        private IsolatedStorageSettings settings;
        private string username, password;
        private bool isLoading;

        public void LoadSettings()
        {
            if (settings != null) { return; }

            settings = IsolatedStorageSettings.ApplicationSettings;
            isLoading = true;

            foreach (var prop in this.GetType().GetProperties())
            {
                if (settings.Contains(prop.Name))
                {
                    try
                    {
                        prop.SetValue(this, settings[prop.Name]);
                    }
                    catch { }
                }
            }

            isLoading = false;
        }

        private void SaveSettings()
        {
            settings.Save();
        }

        public string Username
        {
            get { return username; }
            set
            {
                username = value;
                OnPropertyChanged("Username");
            }
        }

        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                OnPropertyChanged("Password");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string name)
        {
            if (isLoading) { return; }

            try
            {
                settings[name] = this.GetType().GetProperty(name).GetValue(this);
                SaveSettings();
            }
            catch { }

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
}
